package com.kkd.kkdapp.fragment;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.kkd.kkdapp.R;
import com.kkd.kkdapp.activity.MyRegularDebtActivity;
import com.kkd.kkdapp.adapter.MyRegularDebtAdapter;
import com.kkd.kkdapp.http.entity.RegularDebtDetailData;
import com.kkd.kkdapp.http.entity.RegularDebtDetailDataItem;
import com.kkd.kkdapp.http.manager.HttpCallBack;
import com.kkd.kkdapp.http.manager.KkdHttpClient;
import com.kkd.kkdapp.http.manager.KkdHttpMagager;
import com.kkd.kkdapp.utils.AppUtil;
import com.kkd.kkdapp.view.KkdXlistView;
import com.kkd.kkdapp.view.KkdXlistView.KKDScrollListener;

public class MyRegularFragment extends Fragment implements KKDScrollListener {

	private final int CODE_ZERO = 1;
	private final int CODE_ELSE = 2;

	private View mContentView;
	private Activity mCurActivity;
	private ImageView mNullImg;
	private TextView mNullTv;
	private KkdXlistView mXListView;
	private ListView mListView;
	private long pageNO = 1;
	private long pageSize = 10;
	private long pageCount;
	private RegularDebtDetailData data;
	private long dpAmuout;
	private long frozenAssets;
	private long interest;
	private long holdCount;// 持有中个数
	private long transCount;// 转让中个数
	private long outCount;// 已转让个数
	private DecimalFormat df = new DecimalFormat("###,##0.01");
	private MyRegularDebtAdapter adapter;
	private List<RegularDebtDetailDataItem> mList = new ArrayList<RegularDebtDetailDataItem>();

	private boolean REFRESHFLAG = true;
	private boolean isShowToastOnRefresh = false;
	private int type;
	private String text_data_null = "";// 无数据时空页面提示

	private Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case CODE_ZERO:
				// 设置fragment上方界面的数据
				MyRegularDebtActivity myRegularDebtActivity = (MyRegularDebtActivity) mCurActivity;
				myRegularDebtActivity.total_tv.setText(df
						.format(dpAmuout * 0.01));
				myRegularDebtActivity.frozen_tv.setText(df
						.format(interest * 0.01));
				myRegularDebtActivity.tv_select_chiyouzhong.setText("持有中("
						+ holdCount + ")");
				myRegularDebtActivity.tv_select_zhuanrangzhong.setText("转让中("
						+ transCount + ")");
				myRegularDebtActivity.tv_select_yizhuanrang.setText("已转让("
						+ outCount + ")");

				long PageSize = data.getPageSize();
				long totalCount = data.getTotalCount();
				if (totalCount % PageSize != 0) {
					if (totalCount == 0) {
						pageCount = 0;
					} else {
						pageCount = (totalCount / PageSize) + 1;
					}
				} else {
					pageCount = (totalCount / PageSize);
				}
				if (pageNO > pageCount) {
					/*
					 * 此处以下是当刷新后数据为空时，清理页面
					 */
					if (pageNO == 1 && REFRESHFLAG) {
						mList.clear();
						adapter.notifyDataSetChanged();
					}
					/*
					 * 此处以上是当刷新后数据为空时，清理页面
					 */
					mXListView.stopLoadMore(-1);
					if (REFRESHFLAG) {
						mXListView.stopLoadMore(1);
					}
				} else {
					mXListView.setNoMore(false);
					if (pageNO == 1) {
						mList.clear();
					}

					int curSize = 0;
					if (type == 1) {// 持有中
						if (data.getHoldList() != null) {
							mList.addAll(data.getHoldList());
							curSize = data.getHoldList().size();
						}
					} else if (type == 2) {// 转让中
						if (data.getTransList() != null) {
							mList.addAll(data.getTransList());
							curSize = data.getTransList().size();
						}
					} else if (type == 3) {// 已转让
						if (data.getOutList() != null) {
							mList.addAll(data.getOutList());
							curSize = data.getOutList().size();
						}
					}
					adapter.notifyDataSetChanged();
					if (curSize < pageSize) {
						mXListView.stopLoadMore(1);
					} else {
						mXListView.stopLoadMore(0);
					}
				}
				mXListView.stopRefresh();
				mXListView.initState();
				if (REFRESHFLAG) {
					if (mList == null || mList.size() == 0) {
						mNullImg.setVisibility(View.VISIBLE);
						mNullTv.setVisibility(View.VISIBLE);
						mNullTv.setText(text_data_null);
						mNullImg.setImageResource(R.drawable.img_null);
					} else {
						mNullImg.setVisibility(View.GONE);
						mNullTv.setVisibility(View.GONE);
					}
				}

				if (!isShowToastOnRefresh) {
					isShowToastOnRefresh = true;
				}
				break;

			case CODE_ELSE:
				mXListView.stopLoadMore(1);
				mXListView.stopRefresh();

				if (mList == null || mList.size() == 0) {
					mNullImg.setImageResource(R.drawable.img_null_net);
					if (msg.arg1 == KkdHttpClient.NO_NET) {
						mNullTv.setText("网络错误，请稍候下拉刷新重试");
					} else {
						mNullTv.setText("服务异常，请稍候下拉刷新重试");
					}
					mNullImg.setVisibility(View.VISIBLE);
					mNullTv.setVisibility(View.VISIBLE);
				}

				if (isShowToastOnRefresh) {
					String desc = (String) msg.obj;
					if (!TextUtils.isEmpty(desc)) {
						AppUtil.makeToastForCustomer(mCurActivity, desc);
					}
				} else {
					isShowToastOnRefresh = true;
				}
				break;

			default:
				break;
			}
		}
	};

	public static MyRegularFragment getInstance(int type) {
		MyRegularFragment myRegularFragment = new MyRegularFragment();
		Bundle bundle = new Bundle();
		bundle.putInt("type", type);
		myRegularFragment.setArguments(bundle);
		return myRegularFragment;
	}

	@SuppressWarnings("deprecation")
	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		mCurActivity = activity;
		type = getArguments().getInt("type");
		if (type == 1) {// 持有中
			text_data_null = "暂无持有中的定期投资";
		} else if (type == 2) {// 转让中
			text_data_null = "暂无转让中的债权";
		} else if (type == 3) {// 已转让
			text_data_null = "暂无已转让的债权";
		}
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		mContentView = inflater.inflate(R.layout.fragment_myregular, container,
				false);
		initView();
		requestData();
		return mContentView;
	}

	private void initView() {
		mNullImg = (ImageView) mContentView.findViewById(R.id.id_no_content);
		mNullTv = (TextView) mContentView.findViewById(R.id.id_no_content_text);
		mXListView = (KkdXlistView) mContentView.findViewById(R.id.mXListView);
		mXListView.setKKDScrollListener(this);
		mListView = mXListView.mListView;
		mListView.setDividerHeight(0);
		adapter = new MyRegularDebtAdapter(mCurActivity, mList, type);
		mListView.setAdapter(adapter);
		mXListView.startRefresh();
	}

	/**
	 * 请求接口数据
	 */
	private void requestData() {
		KkdHttpMagager.getInstance().getMyRegularDebtManager(type,
				"5002,5003,5004", pageNO, pageSize,
				RegularDebtDetailData.class, new HttpCallBack() {

					@Override
					public void onSuccess(int statusCode, Object responseBody) {
						data = (RegularDebtDetailData) responseBody;
						if (data != null) {
							dpAmuout = data.getDqAmount();
							frozenAssets = data.getFrozenAssets();
							interest = data.getInterest();
							holdCount = data.getHoldCount();
							transCount = data.getTransCount();
							outCount = data.getOutCount();
						}
						mHandler.sendEmptyMessage(CODE_ZERO);
					}

					@Override
					public void onFailure(int statusCode, String desc) {
						Message msg = Message.obtain();
						msg.what = CODE_ELSE;
						msg.obj = desc;
						msg.arg1 = statusCode;
						mHandler.sendMessage(msg);
					}
				});
	}

	@Override
	public void onRefresh() {
		List<Fragment> listFragment = ((MyRegularDebtActivity) mCurActivity)
				.getListFragment();
		for (int i = 0; i < listFragment.size(); i++) {
			((MyRegularFragment) listFragment.get(i)).onSingleRefresh();
		}
	}

	public void onSingleRefresh() {
		mListView.setSelection(0);
		REFRESHFLAG = true;
		pageNO = 1;
		requestData();
	}

	@Override
	public void onLoadMore() {
		REFRESHFLAG = false;
		pageNO++;
		requestData();
	}
}
